package com.memorypalace.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import com.memorypalace.pojo.User;

public class loginFilter implements Filter {

	@Override
	public void destroy() {
		// TODO Auto-generated method stub

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {
		HttpServletRequest servletRequest = (HttpServletRequest) request;
		HttpServletResponse servletResponse = (HttpServletResponse) response;
		HttpSession session = servletRequest.getSession();
		
		// 获得用户请求的URI
		String path = servletRequest.getRequestURI();
		System.out.println(path);

		// 从session里取员工工号信息

		User user = (User) session.getAttribute("user");
		System.out.println("用户信息:" + user);
		// 登陆请求无需过滤

		if (path.indexOf("/memorypalace/checkuser_userandpsd.action") > -1) {
			chain.doFilter(servletRequest, servletResponse);
			return;
		}
		// 登陆页面无需过滤
		if (path.indexOf("/login.jsp") > -1) {
			chain.doFilter(servletRequest, servletResponse);
			return;
		}
		// 注册请求无需过滤
		if (path.indexOf("/register.jsp") > -1) {
			chain.doFilter(servletRequest, servletResponse);
			return;
		}
		if (path.indexOf("/memorypalace/useraction_registerUser.action") > -1) {
			chain.doFilter(servletRequest, servletResponse);
			return;
		}
		if (path.indexOf("/memorypalace/useraction_checkUserName.action") > -1) {
			chain.doFilter(servletRequest, servletResponse);
			return;
		}
		// 判断如果没有取到员工信息,就跳转到登陆页面
		if (user == null || "".equals(user)) { // 跳转到登陆页面
			servletResponse.sendRedirect("/memorypalace/login.jsp");
		} else {
			// 已经登陆,继续此次请求
			
			chain.doFilter(request, response);
		}

	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		// TODO Auto-generated method stub

	}

}
